<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12" style="width: 10px">
        <el-card shadow="hover" :body-style="{ width: '500px' }">
          <template #header>
            <div class="clearfix">
              <span>基础信息</span>
            </div>
          </template>
          <div class="info">
            <div class="info-image" @click="showDialog">
              <img :src="avatarImg" />
              <span class="info-edit">
                <i class="el-icon-lx-camerafill"></i>
              </span>
            </div>

            <div class="info-name">{{ name }}</div>
            <el-form :model="queryformats" label-width="120px">
              <el-form-item label="用户名">
                <el-input
                  v-model="queryformats.data.userName"
                  disabled
                ></el-input>
              </el-form-item>
              <el-form-item label="账号">
                <el-input
                  v-model="queryformats.data.loginName"
                  disabled
                ></el-input>
              </el-form-item>
              <el-form-item label="角色">
                <el-input v-model="queryformats.data.name" disabled></el-input>
              </el-form-item>
            </el-form>
            <!-- <div class="info-desc">不可能！我的代码怎么可能会有bug！</div> -->
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="clearfix">
              <span>账户密码编辑</span>
            </div>
          </template>
          <div class="form-box">
            <el-form
              ref="formRef"
              status-icon
              :model="form"
              label-width="90px"
              :rules="rules"
            >
              <el-form-item label="用户名："> {{ name }} </el-form-item>
              <el-form-item label="旧密码：" prop="old">
                <el-input type="password" v-model="form.old"></el-input>
              </el-form-item>
              <el-form-item label="新密码：" prop="new">
                <el-input type="password" v-model="form.new"></el-input>
              </el-form-item>
              <el-form-item label="确认密码:" prop="password">
                <el-input type="password" v-model="form.password"></el-input>
              </el-form-item>
              <!-- <el-form-item label="个人简介：">
              <el-input v-model="form.desc"></el-input>
            </el-form-item> -->
              <el-form-item>
                <el-button type="primary" @click="onSubmit">确认修改</el-button>
                <el-button @click="onReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="裁剪图片" v-model="dialogVisible" width="400px">
      <vue-cropper
        ref="cropper"
        :src="imgSrc"
        :ready="cropImage"
        :zoom="cropImage"
        :cropmove="cropImage"
        style="width: 100%; height: 400px"
      ></vue-cropper>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="crop-demo-btn" type="primary"
            >选择图片
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="image/*"
              @change="setImage"
            />
          </el-button>
          <el-button type="primary" @click="saveAvatar('blob')"
            >上传并保存</el-button
          >
        </span>
      </template>
      <!-- </el-upload> -->
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref } from "vue";
import VueCropper from "vue-cropperjs";
import "cropperjs/dist/cropper.css";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "../utils/request";
import { useRouter } from "vue-router";
export default {
  name: "useInfo",
  components: {
    VueCropper,
  },
  setup() {
    const name = localStorage.getItem("ms_username");
    const form = reactive({
      old: "",
      new: "",
      password: "",
    });
    const rules = {
      new: [{ required: true, message: "请输入密码", trigger: "blur" }],
      old: [{ required: true, message: "请输入密码", trigger: "blur" }],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    };

    const onSubmit = () => {
      //表单检验
      formRef.value.validate((valid) => {
        if (valid) {
          var params = new URLSearchParams();
          params.append("loginName", name);
          params.append("old", form.old);
          params.append("new", form.new);
          params.append("password", form.password);
          if (form.new != form.password) {
            ElMessage.warning("两次输入密码不一致");
          } else {
            request.post("/user/updateMy", params).then((res) => {
              if (res.code != null) {
                ElMessage.warning(res.msg);
              } else {
                ElMessage.success("成功");
                const router = useRouter();
                localStorage.removeItem("ms_username");
                localStorage.removeItem("ms_loginname");
                // this.name=null;
                router.push("/login");
                params.delete;
              }
            });
          }
        }
      });
    };

    const avatarImg = ref(null);
    const imgSrc = ref("");
    const cropImg = ref("");
    const dialogVisible = ref(false);
    const cropper = ref(null);

    const showDialog = () => {
      dialogVisible.value = true;
      imgSrc.value = avatarImg.value;
    };
    const formData = new FormData();
    const setImage = (e) => {
      const file = e.target.files[0];

      if (!file.type.includes("image/")) {
        return;
      }

      const reader = new FileReader();
      reader.onload = (event) => {
        dialogVisible.value = true;
        imgSrc.value = event.target.result;
        cropper.value && cropper.value.replace(event.target.result);
      };
      //将文件解析成二进制文件
      reader.readAsDataURL(file);
      console.log(file);
      formData.append("file", file);
    };

    const cropImage = () => {
      cropImg.value = cropper.value.getCroppedCanvas().toDataURL();
    };
    //保存图片
    const saveAvatar = (type) => {
      console.log(type);
      avatarImg.value = cropImg.value;
      console.log(formData);
      // localStorage.setItem("ms_username", res.data.userName);
      //           localStorage.setItem("ms_loginname", res.data.loginName);
      //           localStorage.setItem("ms_role", res.data.role);
      //           localStorage.setItem("avatar", res.data.avatar);
      formData.append("loginName", localStorage.getItem("ms_loginname"));
      request
        .post("files/uploadmaig", formData, {
          headers: { "Content-Type": "multipart/form-data" },
        })
        .then((res) => {
          formData.delete("loginName");
          formData.delete("file");
          if (res.code == "18") {
            ElMessage.warning(res.msg);
          } else {
            dialogVisible.value = false;
            getData();
          }
        });
    };
    const query = reactive({
      loginName: "",
    });
    const queryformats = reactive({
      data: {
        sid: "",
        userName: "",
        loginName: "",
        name: "",
        avatar: "",
      },

      // desc: "不可能！我的代码怎么可能会有bug！",
    });

    // 获取表格数据
    const getData = () => {
      query.loginName = localStorage.getItem("ms_loginname");
      request
        .get("/user/queryMy", {
          params: query,
        })
        .then((res) => {
          queryformats.data = res.data;
          avatarImg.value = res.data.avatar;
          localStorage.setItem("avatar", res.data.avatar);
        });
    };
    getData();
    const formRef = ref(null);
    // 重置
    const onReset = () => {
      form.old = null;
      form.new = null;
      form.password = null;
    };

    return {
      rules,
      name,
      form,
      onSubmit,
      cropper,
      avatarImg,
      imgSrc,
      cropImg,
      showDialog,
      dialogVisible,
      setImage,
      formData,
      cropImage,
      saveAvatar,
      query,
      queryformats,
      formRef,
      onReset,
    };
  },
};
</script>

<style scoped>
.info {
  text-align: center;
  padding: 35px 0;
}
.info-image {
  position: relative;
  margin: auto;
  width: 100px;
  height: 100px;
  background: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 50px;
  overflow: hidden;
}
.info-image img {
  width: 100%;
  height: 100%;
}
.info-edit {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
}
.info-edit i {
  color: #eee;
  font-size: 25px;
}
.info-image:hover .info-edit {
  opacity: 1;
}
.info-name {
  margin: 15px 0 10px;
  font-size: 24px;
  font-weight: 500;
  color: #262626;
}
.crop-demo-btn {
  position: relative;
}
.crop-input {
  position: absolute;
  width: 100px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
/* 图片上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader-icon svg {
  margin-top: 74px; /* (178px - 28px) / 2 - 1px */
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>